<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    use HasFactory;

    /**
     * 可批量赋值的属性
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'title',
        'author',
        'publisher',
        'isbn',
        'category',
        'description',
        'image',
        'price',
    ];

    /**
     * 属性的类型转换
     *
     * @var array<string, string>
     */
    protected $casts = [
        'price' => 'decimal:2',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * 获取完整的图片 URL
     *
     * @return string|null
     */
    public function getImageUrlAttribute()
    {
        if (!$this->image) {
            return null;
        }

        // 如果图片路径是完整的 URL，直接返回
        if (filter_var($this->image, FILTER_VALIDATE_URL)) {
            return $this->image;
        }

        // 否则返回基于 storage 的 URL
        return asset('storage/' . $this->image);
    }
}
